package main

import (
	"config"
	"fmt"
	"io"
	"model"
	"model/mysql"
	"os"
	"strings"
	"view"
	"view/md"
)

var (
	username string
	c        config.Config
	out      io.Writer = os.Stdout
)

func main(){
	c=config.Config{
		Host:"127.0.0.1",
		Port:3306,
		Username:"root",
		Password:"",
		DB:"yiiboot",
		Tables:[]string{"admin_file","admin_log"},
		Parama:"charset=utf8&parseTime=true&loc=Local",
		Viewer:md.Name,
		Debug:true,
	}

	repo, err := mysql.NewRepo(&c)
	if err != nil {
		 fmt.Printf("[tsdump] %s", err.Error())
	}
    fmt.Println("starting to dump database;")

	// Get db and table metadata
	dbs, err := getMetadata(repo, c.DB, c.Tables...)
	if err != nil {
		 fmt.Printf("[tsdump] %s", err.Error())
	}

	var f *os.File

	if f, err = os.Create("./1."+c.Viewer); err != nil {
			fmt.Printf("[tsdump] %s", err.Error())
	}
	defer f.Close()
	out = f

	v := view.SelectViewer(c.Viewer)
	if v == nil {
		fmt.Printf("[tsdump] unsupported viewer: %q", c.Viewer)
	}else if err = v.Do(dbs, out); err != nil {
		fmt.Printf("[tsdump] %s", err.Error())
	}
}

// getMetadata 根据目标数据库名和表名，返回目标数据库及其表的元数据。
func getMetadata(repo model.IRepo, db string, tables ...string) (dbs []model.DB, err error) {
	if db == "" && len(tables) > 0 {
		panic("unreachable")
	}
	// 获取所有数据库下的表
	if db == "" {
		dbs,err=repo.GetDBs(nil, false)
		if err!=nil{
			fmt.Println(err.Error())
		}
		return dbs,err
	}


    if strings.Contains(db,"|"){
    	dblist:=strings.Split(db,"|")
    	if len(dblist)!=0{
    		for _,p:=range dblist{
				mydbs, _:= repo.GetDBs(&model.DB{
					Name: p,
				}, false)
				dbs=append(dbs,mydbs...)
			}
		}
	}else{

		// 获取单个数据库下的表
		if tables==nil || len(tables) == 0 {
			return repo.GetDBs(&model.DB{
				Name: db,
			}, false)
		}

		// 获取单个数据库下的若干表
		dbs, err = repo.GetDBs(&model.DB{
			Name: c.DB,
		}, true)
		if err != nil {
			return nil, err
		}
	}


	for i := range dbs {
		for j := range tables {
			tables, err := repo.GetTables(&model.Table{
				DB:   dbs[i].Name,
				Name: tables[j],
			})
			if err != nil {
				return nil, err
			}
			dbs[i].Tables = append(dbs[i].Tables, tables...)
		}
	}
	return dbs, nil
}
